package com.fnzx.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


import com.fnzx.common.enums.ResponseStatusEnum;
import com.fnzx.entity.CooperativeUserEntity;
import com.fnzx.entity.EnterpriseUserEntity;
import com.fnzx.entity.UserEntity;
import com.fnzx.entity.dto.CooperativeUserDto;
import com.fnzx.entity.dto.EnterpriseUserDto;
import com.fnzx.service.EnterpriseUserService;
import com.fnzx.service.UserService;
import com.fnzx.util.PageUtils;
import com.fnzx.util.R;
import com.fnzx.util.common.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-10-23 22:20:00
 */
@RestController
@Api(tags = "企业用户模块")
@RequestMapping("iot/enterpriseuser")
public class EnterpriseUserController {
    @Autowired
    private EnterpriseUserService service;

    @Autowired
    private UserService userService;

    @ApiOperation("信息填报|更改信息")
    @PostMapping("/update")
    public R update(@RequestBody EnterpriseUserEntity entity){
        if (service.updateById(entity)) {
            return R.ok();
        }
        return R.error(ResponseStatusEnum.USER_NOTFOUND.getStatus(),ResponseStatusEnum.USER_NOTFOUND.getMsg());
    }

    @ApiOperation("分页查询")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",paramType = "query",required = true,dataType = "String"),
            @ApiImplicitParam(name = "limit",value = "每页记录数",paramType = "query",required = true,dataType = "String")
    })
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pg = service.queryPage(params);
        return R.ok().put("page", pg);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response){
        //获取需要导出的数据
        List<EnterpriseUserEntity> entities = service.list();
        List<EnterpriseUserDto> dataList = entities.stream().map(record -> {
            EnterpriseUserDto data = new EnterpriseUserDto();
            UserEntity byId = userService.getById(record.getId());
            if (byId!=null){
                BeanUtils.copyProperties(record,data);
                BeanUtils.copyProperties(byId, data);
            }
            return data;
        }).collect(Collectors.toList());
        dataList.removeAll(Collections.singleton(null));
        ExcelUtil<EnterpriseUserDto> excelUtil = new ExcelUtil<>();
        excelUtil.export("企业用户",dataList,response);
    }
}
